package com.hiray.wanandroid.ui.page

import androidx.compose.animation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.Icon
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.unit.ExperimentalUnitApi
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.paging.compose.collectAsLazyPagingItems
import com.hiray.wanandroid.R
import com.hiray.wanandroid.data.SquareViewModel
import kotlinx.coroutines.launch

@ExperimentalAnimationApi
@ExperimentalUnitApi
@Composable
fun SquarePage(viewModel: SquareViewModel = viewModel()) {
    Column(
        Modifier
            .fillMaxSize()
    ) {
        val lazyListItems = viewModel.flow.collectAsLazyPagingItems()
        Box {
            val scope = rememberCoroutineScope()
            val lazyListState = rememberLazyListState()
            LazyColumn(state = lazyListState) {
                items(lazyListItems.itemCount) { index ->
                    HomeFeedItem(lazyListItems[index]!!)
                }
            }
            var floatingActionButtonVisible by remember { mutableStateOf(false) }
            floatingActionButtonVisible = lazyListState.firstVisibleItemIndex > 4
            androidx.compose.animation.AnimatedVisibility(
                visible = floatingActionButtonVisible, modifier = Modifier
                    .align(Alignment.BottomEnd)
                    .padding(bottom = 16.dp, end = 16.dp),
                enter = fadeIn() + slideIn(initialOffset = { IntOffset(0, it.height) }),
                exit = fadeOut() + slideOut(targetOffset = { IntOffset(0, it.height) })
            ) {
                FloatingActionButton(onClick = {
                    floatingActionButtonVisible = false
                    scope.launch { lazyListState.scrollToItem(0) }
                }) {
                    Icon(
                        imageVector = ImageVector.vectorResource(id = R.drawable.back_to_top),
                        contentDescription = "",
                        Modifier.size(24.dp),
                        tint = Color.White
                    )
                }
            }

        }
    }
}